
"use client";

import { useState, useMemo, useEffect } from 'react';
import { Input } from '@/components/ui/input';
import { Search } from 'lucide-react';
import { PostCard } from '@/components/post-card';
import { getPosts, Post } from '@/lib/posts';

export default function Home() {
  const [searchQuery, setSearchQuery] = useState('');
  const [posts, setPosts] = useState<Post[]>([]);

  // Function to refresh posts from storage
  const refreshPosts = () => {
    setPosts(getPosts());
  };

  useEffect(() => {
    refreshPosts();

    // Listen for custom event to refresh posts
    const handleStorageChange = () => {
      refreshPosts();
    };
    
    window.addEventListener('storage', handleStorageChange);
    window.addEventListener('post-deleted', handleStorageChange);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('post-deleted', handleStorageChange);
    };
  }, []);

  const filteredPosts = useMemo(() => {
    if (!searchQuery) {
      return posts;
    }
    return posts.filter(
      (post) =>
        post.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        post.content.toLowerCase().includes(searchQuery.toLowerCase()) ||
        post.tags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()))
    );
  }, [searchQuery, posts]);
  
  const handlePostDelete = () => {
    // Dispatch a custom event to notify other components
    window.dispatchEvent(new CustomEvent('post-deleted'));
    refreshPosts();
  };

  return (
    <div className="space-y-8">
      <div className="relative w-full max-w-xl mx-auto">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
        <Input
          type="search"
          placeholder="搜索文章..."
          className="pl-10 text-lg py-6 rounded-full shadow-md"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
      </div>

      <div className="grid gap-8 md:grid-cols-2 lg:grid-cols-3">
        {filteredPosts.length > 0 ? (
          filteredPosts.map((post) => (
            <PostCard key={post.slug} post={post} onPostDelete={handlePostDelete} />
          ))
        ) : (
          <p className="col-span-full text-center text-muted-foreground mt-8">没有找到相关文章。</p>
        )}
      </div>
    </div>
  );
}
